package com.hxx.day7;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

/**
 * 去重需要同时覆盖两个方法：hashCode()和equals()
 */
public class TestDemo3 {
    public static void main(String[] args) {
        Set set = new HashSet();
        Emp emp1 = new Emp(1001, "张三", 20);
        Emp emp2 = new Emp(1001, "张三", 20);
        set.add(emp1);
        set.add(emp2);
        System.out.println(set);
    }

    /**
     * 同一个对象的hashCode()值是相同的
     * 不同对象的hashCode()值可能相同
     */
    @Test
    public void testHashSet(){
       String str1 = "hello";
       String str2 = new String("hello");
       System.out.println(str1.hashCode());
       System.out.println(str2.hashCode());
    }
}

class Emp{
    private Integer id;
    private String name;
    private int age;

    public Emp() {
    }

    // 重写hashCode()方法
    @Override
    public int hashCode() {
        return 100;
    }
    // 重写equals()方法
    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return true;
        }
        if(obj instanceof Emp){
            Emp emp = (Emp) obj;
            if(id.equals(emp.id) && name.equals(emp.name)){
                return true;
            }
        }
        return false;
    }

    public Emp(Integer id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


























